import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:latlong2/latlong.dart';
import 'package:situation/data/bus/intercom_bus.dart';
import 'package:situation/data/channel/intercom_channel.dart';
import 'package:situation/resources/assets.dart';
import 'package:situation/widgets/mk_load_image.dart';

class MapTrack extends StatefulWidget {
  const MapTrack({super.key});

  @override
  State<MapTrack> createState() => _MapTrackState();
}

class _MapTrackState extends State<MapTrack> {
  List<LatLng> _trackPoints = [];
  bool _isRecording = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    listenLocation();
  }

  void listenLocation() {
    IntercomBus.to.getBus().on<IntercomEvent>().listen((event) {
      if (event.event == IntercomChannel.to.LOCATION_EVENT) {
        if (!_isRecording) {
          // 打印 event.data 的类型
          var d;
          if(event.data.runtimeType == String){
            d = jsonDecode(event.data);
          }else {
            d = event.data;
          }
           var lat = d['lat'];
           var lon = d['lon'];
          final newPoint = LatLng(
              lat,lon
          );
          _trackPoints.add(newPoint);
        }
      }
    });
  }

  void _toggleRecording() async {
    if (!_isRecording) {
      SmartDialog.showNotify(msg: "开始记录", notifyType: NotifyType.success);
    } else {
      SmartDialog.showNotify(msg: "结束记录", notifyType: NotifyType.success);
    }
    setState(() {
      _isRecording = !_isRecording;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Align(
          alignment: Alignment.bottomRight,
          child: Container(
            margin: EdgeInsets.only(right: 16, bottom: 230),
            width: 40,
            height: 40,
            padding: EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: _isRecording ? Colors.red : Colors.lightBlue,
              borderRadius: BorderRadius.circular(8),
            ),
            child: GestureDetector(
              onTap: _toggleRecording,
              child: AnimatedSwitcher(
                duration: Duration(milliseconds: 300),
                child:
                    _isRecording
                        ? Icon(Icons.stop, color: Colors.white)
                        : MkLoadImage(Assets.commonRote, width: 30),
              ),
            ),
          ),
        ),

        _trackPoints.length > 0
            ? PolylineLayer(
              polylines: [
                Polyline(
                  points: _trackPoints,
                  color: Colors.blue.withOpacity(0.7),
                  strokeWidth: 4,
                ),
              ],
            )
            : Container(),
      ],
    );
  }
}
